(function() {
    angular.module('BlurAdmin.pages.noticeM')
        .controller('NewNoticemCtrl', NewNoticemCtrl);

    function NewNoticemCtrl($scope, $ShareData, $datepicker, $qupload, $http, $mydialog, $log, $filter, $myconfig) {
        var notice_id = $scope.notice_id = $ShareData.getNewnoticeM(); //获取上传过来的id，如果为空则是新增
        //日期插件
        $scope.format = "yyyy/MM/dd";
        $scope.altInputFormats = ['yyyy/M!/d!'];
        $scope.dat = {
            dat3: $datepicker.dataNew(),
        };
        //设置发布日期
        var dateAsString = $filter('date')(new Date(), "yyyy-MM-ddThh:mm");
        $scope.new_d = dateAsString;
        $scope.Noticem_data = {
            "title": "", //通知标题
            "summary": "", //通知摘要
            "content": "", //通知内容
            "publish": false, //是否已经发布布尔值
            "timely": true, //是否及时发布布尔值
            "push": true, //是否推送消息布尔值
            "pubtime": new Date() //消息发布时间
        };

        var is_Timing_type = true;
        $scope.Submit = function() { //点击完成按钮
            if (is_Timing_type) {
                Testing();
            }
        }

        //选择是否推送消息
        $scope.Push_f = function() {
            $scope.Noticem_data.push = !$scope.Noticem_data.push;
        }

        //判断及时发送，定时发送时间
        $scope.is_Timing = function(val) {
            if (is_Timing_type) {
                $scope.Noticem_data.timely = val;
            }
        }


        function Testing() { //检测条件是否满足
            var opt = $scope.Noticem_data;
            if (!opt.title) {
                return $mydialog.fail('请添加标题');
            }
            if (opt.title.length > 20) {
                return $mydialog.fail('标题不能大于20个字');
            }
            if (!opt.summary) {
                return $mydialog.fail('请添加摘要');
            }
            if (opt.summary.length > 100) {
                return $mydialog.fail('摘要不能大于100个字');
            }
            if (!opt.content) {
                return $mydialog.fail('请添加通知内容');
            }
            if (opt.content.length > 10000) {
                return $mydialog.fail('资讯内容不能大于10000个字符');
            }
            SendOut(); //新增通知
        }


        function SendOut() { //发送新增/修改通知请求
            //判断是及时发布，定时发布，并且修改发布时间
            $scope.Noticem_data.pubtime = $scope.Noticem_data.timely ? new Date() : ((typeof($scope.new_data)) == 'object' ? $scope.new_data : $scope.Noticem_data.pubtime);
            var o = JSON.stringify($scope.Noticem_data);
            var opt = JSON.parse(o);
            //判定时发送转化时间格式
            var data1 = document.getElementById("dat3") ? document.getElementById("dat3").value : null;
            if (data1) {
                data1 = data1.replace('T', " ");
                data1 = data1 + ':00';
                opt.pubtime = data1; //赋值时间
            }
            //比较时间是否小于当前时间
            if (!$scope.Noticem_data.timely) {
                if ($scope.new_data < (new Date())) {
                    return $mydialog.fail('定时时间不能小于当前时间');
                }
            }

            //$myconfig.api.Notice_add_notice;//新增通知
            //$myconfig.api.Notice_update_notice 编辑通知
            opt.createtime && delete opt.createtime;
            opt.id && (opt.notice_id = opt.id) && delete opt.id;

            var url = notice_id ? $myconfig.api.Notice_update_notice : $myconfig.api.Notice_add_notice; //新增通知/编辑通知
            is_Timing_type = false;

            $http.post(url, opt)
                .then(function(res) {
                    console.log(res);
                    is_Timing_type = true;
                    if (res.data.success) {
                        $scope.search_data(); //刷新通知列表，父级定义方法；
                        $scope.opt_close(); //关闭弹出窗口
                        return $mydialog.success("设置成功");
                    } else {
                        return $mydialog.fail(res.data.data);
                    }
                });
        };

        /* 编辑通知 */
        $scope.edit = function() { //获取通知详情
            $http.get($myconfig.api.Notice_notice_info + "?notice_id=" + notice_id)
                .then(function(res) {
                    if (res.data.success) { //成功
                        $scope.Noticem_data = res.data.data;
                        $scope.Noticem_data.pubtime;
                        var dateAsString = $filter('date')($scope.Noticem_data.pubtime, "yyyy-MM-ddThh:mm");
                        console.log(dateAsString);
                        $scope.new_d = dateAsString;
                    } else {
                        return $mydialog.fail(res.data.data);
                    }
                });
        }

        // 获取七牛touken

        function qi_t() {
            $http.get($myconfig.api.QiNiu_token).then(function(res) {
                console.log(res);
                $scope.qi_token_mun = res.data.token;
                $scope.qi_key = res.data.key;
            })
        }
        qi_t();
        //七牛图片上传
        $scope.selectFiles = [];
        $scope.context_img_fn = function(val) { //红包宣传图 1 ，红包主图为2 
            if (is_img) {
                $scope.context_img = val;
            }
        };
        var start = function(index) {
            $scope.selectFiles[index].progress = {
                p: 0
            };
            $scope.selectFiles[index].upload = $qupload.upload({
                key: $scope.qi_key,
                file: $scope.selectFiles[index].file,
                token: $scope.qi_token_mun
            });
            $scope.selectFiles[index].upload.then(function(response) {
                $log.info(response);
                var url = $myconfig.api.Qiniu_url + response.key;
                //插入富文本框
                $('#summernote').summernote('insertImage', url)
                qi_t();
                is_img = true; //图片上传成功后可以继续上传图片

            }, function(response) {
                // upload failure
                $log.info(response);
            }, function(evt) {
                // progress
                //evt.totalSize文件大小
                // evt.loaded已上传多少
                var mum = Math.floor(100 * evt.loaded / evt.totalSize);
                //  $scope.context_img == 1 ? ($scope.mystyle.posters.width = mum + '%') : ($scope.mystyle.mainpic.width = mum + '%');
                $scope.selectFiles[index].progress.p = Math.floor(100 * evt.loaded / evt.totalSize);


            });
        };
        $scope.abort = function(index) {
            $scope.selectFiles[index].upload.abort();
            $scope.selectFiles.splice(index, 1);
        };

        // 判断是否点击了上传图片
        var is_img = true;
        $scope.onFileSelect = function($files) {
            if (!is_img) {
                return
            }
            var offsetx = $scope.selectFiles.length;
            for (var i = 0; i < $files.length; i++) {
                $scope.selectFiles[i + offsetx] = {
                    file: $files[i]
                };
                start(i + offsetx);
            }
        };
        /* 七牛图片上传结束 */

        //富文本编辑器
        var HelloButton = function(context) { //自定义图片上传按钮
            var ui = $.summernote.ui;
            var button = ui.button({
                contents: '<span  class="glyphicon glyphicon-picture"></span> 图片',
                tooltip: '图片',
                click: function() {
                    $scope.context_img = 1; //详情页图片为1 ，轮播图为2
                    document.getElementById('asd1').click();
                }
            });

            return button.render(); // return button as jquery object 
        }

        $scope.options = {
            height: 300,
            focus: true,
            airMode: false,
            toolbar: [
                // ['edit', ['undo', 'redo']],
                ['headline', ['style']],
                ['style', ['bold', 'italic', 'underline', 'superscript', 'subscript', 'strikethrough', 'clear']],
                // ['fontface', ['fontname']],
                ['textsize', ['fontsize']],
                ['fontclr', ['color']],
                ['alignment', ['ul', 'ol', 'paragraph', 'lineheight']],
                ['height', ['height']],
                // ['table', ['table']],
                //['insert', ['link', 'picture']],
                ['mybutton', ['hello']]
                // ['view', ['fullscreen', 'codeview']]
                // ['help', ['help']]
            ],
            buttons: {
                hello: HelloButton
            }
        };


        notice_id && $scope.edit(); //判断是否是编辑,新增的没有值



    };
})();